package com.leyou.item.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.item.dto.CategoryDTO;
import com.leyou.item.entity.Category;
import com.leyou.item.entity.CategoryBrand;
import com.leyou.item.mapper.CategoryMapper;
import com.leyou.item.service.CategoryBrandService;
import com.leyou.item.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private CategoryBrandService categoryBrandService;
    /**
     * 根据品牌id，查询商品分类的集合
     * @param brandId
     * @return
     */
    @Override
    public List<CategoryDTO> queryCategoryByBrandId(Long brandId) {
        //先根据品牌id在中间表查询中间表的集合
        List<CategoryBrand> categoryBrandList = categoryBrandService.query().eq("brand_id", brandId).list();
        if (CollectionUtils.isEmpty(categoryBrandList)){
            return Collections.emptyList();
        }
        //再从中间表中获取商品分类id的集合
        List<Long> categoryIds = categoryBrandList.stream()
                .map(CategoryBrand::getCategoryId)
                .collect(Collectors.toList());
        //根据商品分类id获取商品分类
        List<Category> categories = listByIds(categoryIds);
        //转换为dto
        List<CategoryDTO> categoryDTOS = CategoryDTO.convertEntityList(categories);
        return categoryDTOS;
    }
}
